#region

using Microsoft.Extensions.DependencyInjection;
using Microsoft.OpenApi.Models;

using Swashbuckle.AspNetCore.Filters;
using Swashbuckle.AspNetCore.SwaggerGen;

#endregion

namespace Leo.Core.Swagger
{
    /// <summary>
    ///     Swagger 默认配置
    /// </summary>
    public static class SwaggerOptionsExtensions
    {
        /// <summary>
        ///     文档说明相关配置
        /// </summary>
        /// <param name="options"></param>
        public static void ConfigApiDocument(this SwaggerGenOptions options)
        {
            if (ApiConfig.GroupList != null)
            {
                ApiConfig.GroupList.ForEach(x =>
                {
                    var groupOpenApiInfo = Helper.GetOpenApiInfo(x) as OpenApiInfo;
                    options.SwaggerDoc(x, groupOpenApiInfo);
                });
            }
            options.DocInclusionPredicate(Helper.CheckApiInGroup);
            options.DocumentFilter<DescriptionDocumentFilter>();
            options.ConfigXmlDocument();
        }

        private static void ConfigXmlDocument(this SwaggerGenOptions options)
        {
            //加载XML文档
            var documentFileNameList = Helper.GetXmlDocumentFileNameList();
            foreach (var documentFileName in documentFileNameList)
            {
                options.IncludeXmlComments(documentFileName);
            }
        }

        /// <summary>
        ///     配置JWT认证
        /// </summary>
        /// <param name="options"></param>
        public static void ConfigSecurity(this SwaggerGenOptions options)
        {
            var security = new OpenApiSecurityScheme
            {
                Description = "JWT模式授权，请输入 Bearer {Token} 进行身份验证",
                Name = "Authorization",
                Scheme = "Bearer",
                In = ParameterLocation.Header,
                Type = SecuritySchemeType.ApiKey
            };
            options.AddSecurityDefinition("JWT", security);
            options.AddSecurityRequirement(new OpenApiSecurityRequirement
            {
                {
                    new OpenApiSecurityScheme
                    {
                        Reference = new OpenApiReference { Type = ReferenceType.SecurityScheme, Id = "JWT" }
                    },
                    new string[] { }
                }
            });
            options.OperationFilter<AddResponseHeadersFilter>();
            //options.OperationFilter<AppendAuthorizeToSummaryOperationFilter>(); //不显示权限验证名称
            //options.OperationFilter<SecurityRequirementsOperationFilter>(); //不要取消注释
        }
    }
}